package com.jinxin.platform.cdcardpassmgr.task;

import com.alibaba.fastjson.JSONObject;
import com.jinxin.platform.base.common.pojo.JsonResult;
import com.jinxin.platform.cdcardpassmgr.bean.CdcardpassmgrCard;
import com.jinxin.platform.cdcardpassmgr.bean.CdcardpassmgrDevice;
import com.jinxin.platform.cdcardpassmgr.bean.CdcardpassmgrRecord;
import com.jinxin.platform.cdcardpassmgr.rpc.CdcardpassmgrRpc;
import com.jinxin.platform.cdcardpassmgr.service.ICardpassmgrCardService;
import com.jinxin.platform.cdcardpassmgr.service.ICardpassmgrDeviceService;
import com.jinxin.platform.cdcardpassmgr.service.ICardpassmgrRecordService;
import com.jinxin.platform.cdcardpassmgr.utils.DateUtil;
import com.jinxin.platform.cdcardpassmgr.utils.NumConvertUtil;
import com.jinxin.platform.cdcardpassmgr.utils.Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;

/**
 * All rights Reserved, Designed By www.beonelot.com
 *
 * @version: V1.0
 * @Copyright: www.beonelot.com Inc. All rights reserved.
 * @Description： 这种定时任务的方式只能在项目启动的时候创建，而不能动态的创建和更新定时任务，所以改为quartz的方式
 * @Date: 2021-07-07
 * @Author: Lingnan
 **/
//@Component
@Slf4j
public class SchedultaskController implements SchedulingConfigurer {
    @Autowired
    private ICardpassmgrDeviceService deviceService;
    @Autowired
    private ICardpassmgrCardService cardService;
    @Autowired
    private ICardpassmgrRecordService recordService;
    @Autowired
    private CdcardpassmgrRpc cdcardpassmgrRpc;

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        long start = System.currentTimeMillis();
        try {
            HashMap param = new HashMap();
            param.put("configStatus",1);// 查询已配置的
            List<CdcardpassmgrDevice> list = deviceService.list(param);
//            HashMap<String,CdcardpassmgrCard> cardMap = new HashMap<>();
//            if(list.size() > 0){
//                List<CdcardpassmgrCard> cardList = cardService.list(new HashMap());
//                cardList.forEach(item->{
//                    cardMap.put(item.getCardNum(),item);
//                });
//            }
            for (CdcardpassmgrDevice device : list) {
                Integer intervalSecond = device.getIntervalSecond();
                if(intervalSecond == null || intervalSecond <= 0){
                    continue;
                }
                scheduledTaskRegistrar.addTriggerTask(
                        //1.添加任务内容(Runnable)，可以为方法
                        () -> {
                            String serialNum = device.getSerialNum();
                            String password = device.getPassword();
                            String recordCode = device.getRecordCode();
                            Integer recordIndex = Integer.parseInt(device.getRecordIndex());
                            Integer readCount = Integer.parseInt(device.getReadCount());
                            if(readCount <= 0){
                                return;
                            }
                            JsonResult jsonResult = cdcardpassmgrRpc.readTheRecord(serialNum, password, recordCode, recordIndex, readCount, device.getDeviceMac());
                            //JsonResult jsonResult = JsonResult.ok("success","{\"r2\":\"00 00 00 01 00 00 00 00 01 20 11 13 16 47 34 03 01 00 00 00 02 00 00 AA AA AA 20 11 13 16 47 34 05 0C 00 00 00 03 00 00 AA AA AA 20 11 13 16 47 34 06 0C 00 00 00 04 00 00 AA AA AA 20 11 13 16 47 34 07 0C 00 00 00 05 00 00 AA AA AA 20 11 13 16 47 34 08 0C 00 00 00 06 00 00 AA FF AA 20 11 13 16 47 45 01 0C 00 00 00 07 00 00 AA FF AA 20 11 13 16 47 45 02 0C 00 00 00 08 00 00 AA FF AA 20 11 13 16 47 45 03 0C 00 00 00 09 00 00 7F FF FF 20 11 13 16 47 46 01 01 00 00 00 0A 00 00 7F FF FF 20 11 13 16 47 46 02 01 00 00 00 0B 00 00 7F FF FF 20 11 13 16 47 46 03 01 00 00 00 0C 00 00 7F FF FF 20 11 13 16 47 46 04 01 00 00 00 0D 00 00 00 00 07 20 11 13 16 47 47 04 0C 00 00 00 0E 00 00 03 FF FF 20 11 13 16 47 47 04 0C 00 00 00 0F FF FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 10 FF FF FF FF FF FF FF FF FF FF FF FF FF\",\"code\":\"0\",\"r1\":\"00 00 00 10\"}");
                            if(jsonResult.getSuccess()){
                                String dataStr = jsonResult.getData().toString();
                                JSONObject jsonObject = JSONObject.parseObject(dataStr);
                                String r2Str = jsonObject.getString("r2");
                                log.info("通行记录返回的r2: " + r2Str);
                                if(!StringUtils.isEmpty(r2Str)){
                                    for (int i = 0; i < readCount; i++) {
                                        String lineStr = r2Str.substring(50 * i + i, 50 * (i + 1) + i);
                                        String index = lineStr.substring(0, 11).replace(" ","");
                                        String cardNum = lineStr.substring(12, 26).replace(" ","");
                                        if("FFFFFFFFFF".equals(cardNum)){
                                            break;
                                        }
                                        String timeStr = "20"+lineStr.substring(27, 44).replace(" ","");
                                        String doorStr = lineStr.substring(45, 47).replace(" ","");
                                        String status = lineStr.substring(48, 50).replace(" ","");
                                        if(!"01".equals(status)){ // 01合法开门
                                            continue;
                                        }
                                        String id = timeStr + doorStr;
                                        CdcardpassmgrRecord record = recordService.selectById(id);
                                        if(record == null){
                                            String cardNumStr = NumConvertUtil.hexStringToInt(cardNum,8);
                                            HashMap param2 = new HashMap();
                                            param2.put("cardNum",cardNumStr);
                                            CdcardpassmgrCard card = cardService.selectOne(param2);
                                            if(card != null){ //只有登记了的卡号才插入数据库
                                                record = new CdcardpassmgrRecord();
                                                record.setId(id);
                                                record.setCardNum(cardNumStr);
                                                record.setTypeId(card.getTypeId());
                                                record.setType(card.getType());
                                                record.setCarNum(card.getCarNum());
                                                int direction = Utils.isOdd(Integer.parseInt(doorStr)) ? 1 : 2; // 通行方向1进2出
                                                record.setPassTime(DateUtil.timeString2LocalDateTime(timeStr,"yyyyMMddHHmmss"));
                                                record.setDirection(direction);
                                                record.setProjectId(card.getProjectId());
                                                recordService.saveOrUpdate(record,true);
                                            }
                                        }
                                    }
                                }
                            }
                        },
                        //2.设置执行周期(Trigger)
                        triggerContext -> {
                            String cron = "0 0/"+intervalSecond+" * * * ? ";
                            //3 返回执行周期(Date)
                            return new CronTrigger(cron).nextExecutionTime(triggerContext);
                        }
                );
            }

        }catch (Exception e){
            log.info(e.toString());
        }
        log.info("通行记录数据插入耗时: " + (System.currentTimeMillis()-start)/1000/60);
    }
}
